<template>
  <view class="app-container add-guest-page">
    <view class="form">
      <u-form labelPosition="left" :model="userInfo" :rules="rules" ref="uForm" labelWidth="80">
        <u-form-item label="姓名" prop="memberName" borderBottom required>
          <u-input v-model="userInfo.memberName" border="none" :disabled="!userInfo.isEditable"></u-input>
        </u-form-item>
        <u-form-item label="联系手机" prop="memberPhone" borderBottom>
          <u-input v-model="userInfo.memberPhone" border="none"></u-input>
        </u-form-item>
        <u-form-item label="身份证号" prop="idCard" borderBottom required>
          <u-input v-model="userInfo.idCard" border="none" :disabled="!userInfo.isEditable"></u-input>
        </u-form-item>
        <u-form-item label="关系" prop="memberRelation" borderBottom>
          <u-input v-model="userInfo.memberRelationName" border="none" @tap="relationPickerShow = true"
                   readonly></u-input>
        </u-form-item>
        <view class="tips">
          <text>实名认证后不能修改姓名和身份证号</text>
        </view>
      </u-form>
      <view class="btns">
        <view class="btn">
          <u-button type="primary" @click="submit" color="#FF7947">提交</u-button>
        </view>
<!--        <view class="btn" v-if="memberId">-->
<!--          <u-button type="primary" @click="handleDel" color="#FF7947">删除</u-button>-->
<!--        </view>-->
      </view>
      <u-picker :show="relationPickerShow" :columns="columns" keyName="label" @confirm="confirmRelation"
                :immediate-change="true"
                @cancel="close"></u-picker>
    </view>

  </view>
</template>

<script>
import {addMember, deleteMember, memberDetail, updateMember} from "@/api/manager/order";
import storage from "@/utils/storage";
import constant from "@/utils/constant";
import {showConfirm} from "@/utils/common";
import store from "@/store";

export default {
  dicts: ['member_relation'],
  data() {
    return {
      memberId: null,
      relationPickerShow: false,
      columns:
          [[
            {"label": "配偶", "value": "1"},
            {"label": "子女", "value": "2"},
            {"label": "父母", "value": "3"},
            {"label": "家属", "value": "4"},
            {"label": "合伙人", "value": "5"},
            {"label": "其他", "value": "6"}
          ]],
      userInfo: {
        memberName: '',
        memberPhone: '',
        idCard: '',
        memberRelation: '',
        isEditable: true
      },
      rules: {
        memberName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: ['blur', 'change']
          },
        ],
        memberPhone: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return true;
              }
              return uni.$u.test.mobile(value);
            },
            message: '请输入正确的手机号',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          }
        ],
        idCard: [
          {
            required: true,
            message: '请输入身份证号',
            trigger: ['blur', 'change']
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.idCard(value);
            },
            message: '请输入正确的身份证号',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          }]

      }
    };
  },
  onLoad(options) {
    const memberId = options.memberId;
    if (memberId) {
      this.memberId = memberId
      this.getMemberDetail(memberId)
    }
    // 设置页面标题
    const title = memberId ? '修改信息' : '新增同住人';
    uni.setNavigationBarTitle({
      title: title
    });
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)

  },
  methods: {
    // 选择关系
    confirmRelation(e) {
      this.userInfo.memberRelation = e.value[0].value
      this.userInfo.memberRelationName = e.value[0].label
      this.relationPickerShow = false
    },
    close() {
      this.relationPickerShow = false
    },
    getMemberDetail(memberId) {
      memberDetail(memberId).then(res => {
        this.userInfo = res.data
        const memberRelation = res.data.memberRelation;
        if (memberRelation) {
          this.userInfo.memberRelationName = this.dict.type.member_relation.find(item => {
            return item.value === memberRelation
          }).label
        }
        // 是否可编辑 实名认证后不能修改姓名和身份证号
        // 实名状态：1已实名 2未实名
        this.userInfo.isEditable = this.userInfo.authState === '2'
      })
    },
    submit() {
      this.$refs.uForm.validate().then(validate => {
        if (this.memberId) {
          // 更新
          this.updateMember()
        } else {
          // 新增
          this.addMember()
        }
      }).catch(errors => {
        // uni.$u.toast('校验失败')
      })
    },
    handleDel() {
      showConfirm('是否确定此删除入住人').then(res => {
        if (res.confirm) {
          this.deleteMember(this.memberId)
        }
      })
    },
    deleteMember(memberId) {
      deleteMember(memberId).then(res => {
        this.$modal.msg("删除成功");
        // 延迟0.5后跳转到list
        setTimeout(() => {
          this.$tab.redirectTo("/pages/manager/guest/guest-list")
        }, 500)
      })
    },
    addMember() {
      const order = storage.get(constant.room);
      if (!order.houseId || !order.orderId) {
        this.$modal.msgError('请先选择房间!');
      }
      this.userInfo.orderId = order.orderId;
      this.userInfo.houseId = order.houseId;
      addMember(this.userInfo).then(res => {
        this.$modal.msg("添加成功");
        // 延迟0.5
        setTimeout(() => {
          let params = {
            // 页面标题
            navigationBarTitleText: '提交成功',
            // 标题
            title: '添加成功',
            //副标题
            subTitle: '成功新增同住人',
            // 按钮组
            buttonList: [
              {
                text: '返回房管家',
                type: 'primary',
                plain: false,
                size: 'mini',
                url: '/pages/manager/index',
                urlType: 'switchTab'
              },
              {
                text: '返回入住人信息',
                type: 'primary',
                plain: true,
                size: 'mini',
                url: '/pages/manager/tenant/tenant-list',
                urlType: 'navigateBack'
              }
            ],
          }
          this.$tab.redirectTo("/pages/common/success/success" + "?params=" + JSON.stringify(params));
        }, 500)
      })
    },
    updateMember() {
      updateMember(this.userInfo).then(res => {
        this.$modal.msg("修改成功");
        setTimeout(() => {
          this.$tab.navigateBack()
        }, 500)
      })

    }
  }
}
</script>

<style lang="scss">
.add-guest-page {
  .form {
    padding: 20rpx;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin: 16px;

    .btns {
      margin-top: 20rpx;

      .btn:last-child {
        margin-top: 20rpx;
      }
    }

    .tips {
      margin: 20rpx 0;
      text-align: center;
      color: #999;
    }
  }

}

</style>
